package com.wzapp.sitposture.eshop.endpoint;

import com.wzapp.sitposture.common.base.BaseEndpoint;
import com.wzapp.sitposture.common.base.HeaderParam;
import com.wzapp.sitposture.common.error.CustomizedException;
import com.wzapp.sitposture.common.restful.RestfulResult;
import com.wzapp.sitposture.common.util.ToolUtil;
import com.wzapp.sitposture.eshop.pay.properties.AlipayProperties;
import com.wzapp.sitposture.eshop.pay.properties.WeChatPaymentProperties;
import com.wzapp.sitposture.eshop.service.IdGeneratorService;
import com.icanpay.PaymentSetting;
import com.icanpay.enums.GatewayType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URI;
import java.util.HashMap;

/**
 * 功能: h5<br/>
 *
 * @author yuxiaguang
 * @create 2018-06-20 16:46
 * @return
 **/
@RestController
@RequestMapping("/eShop/orderPays")
public class WapPayEndpoint extends BaseEndpoint{

	private static final Logger log = LoggerFactory.getLogger(WapPayEndpoint.class);

	@Autowired
	private AlipayProperties alipayProperties;

	@Autowired
	private WeChatPaymentProperties weChatPaymentProperties;

	@Autowired
	IdGeneratorService idGeneratorService;

	@GetMapping("/ali")
	public String Alipay(@RequestParam("orderCode")String orderCode, @RequestParam("amount")String amount) throws IOException, Exception {

	    amount = new String(amount.getBytes("ISO-8859-1"),"UTF-8");

		PaymentSetting paymentSetting = new PaymentSetting(GatewayType.Alipay);
		paymentSetting.getMerchant().setAppId(alipayProperties.getAppid());
		paymentSetting.getMerchant().setEmail(
				alipayProperties.getSeller_email());
		paymentSetting.getMerchant().setPartner(alipayProperties.getPartner());
		paymentSetting.getMerchant().setKey(alipayProperties.getKey());
		paymentSetting.getMerchant().setPrivateKeyPem(
				alipayProperties.getPrivatekeypem());
		paymentSetting.getMerchant().setPublicKeyPem(
				alipayProperties.getPublicKeypem());
		paymentSetting.getMerchant().setNotifyUrl(
				new URI(alipayProperties.getNotifyurl()));
		paymentSetting.getMerchant().setReturnUrl(
				new URI(alipayProperties.getReturnurl()));

        paymentSetting.getOrder().setOrderAmount(new BigDecimal(amount));
        paymentSetting.getOrder().setOrderNo(orderCode);
        paymentSetting.getOrder().setSubject("测试test");

        String body = paymentSetting.wapPayment(null);
        log.debug("=========Alipay===========body:" + body);
        return body;
	}

	@SuppressWarnings("serial")
	@GetMapping("/wechat")
	public ResponseEntity WeChatPayment(@RequestParam("productId") String productId,
										@RequestParam("count")Integer count,
										HttpSession session) throws IOException, Exception {
		if(log.isDebugEnabled()) {
			log.debug("WapPayController WeChatPayment start args: productId = " + productId + ", count = " + count);
		}

		if (ToolUtil.isEmpty(productId)) {
			throw new CustomizedException("eshop.param.productid.blank");
		}

		HeaderParam headerParam = getHeaderParam();
		String userId = headerParam.getUserId();

		if(ToolUtil.isEmpty(count)){
			count = 1;
		}

		// TODO 创建订单

		PaymentSetting paymentSetting = new PaymentSetting(GatewayType.WeChatPayment);

		paymentSetting.getMerchant().setAppId(weChatPaymentProperties.getAppid());
		paymentSetting.getMerchant().setPartner(weChatPaymentProperties.getMch_id());
		paymentSetting.getMerchant().setKey(weChatPaymentProperties.getKey());
		paymentSetting.getMerchant().setNotifyUrl(new URI(weChatPaymentProperties.getNotifyurl()));
		paymentSetting.getMerchant().setReturnUrl(new URI(weChatPaymentProperties.getReturnurl()));

		String orderCode = idGeneratorService.generatorOrderCode();
		paymentSetting.getOrder().setOrderNo(orderCode);
		paymentSetting.getOrder().setOrderAmount(new BigDecimal("0.01"));
		paymentSetting.getOrder().setSubject("wechatpayment");
		paymentSetting.getOrder().setSceneInfo(
				"{\"h5_info\": {\"type\":\"Wap\",\"wap_url\": \"http://test.everygod.com\",\"wap_name\": \"课程购买\"}}");
		// 可以在这里传跳转页面url，如果不传则默认取配置中的returnurl
		// https://pay.weixin.qq.com/wiki/doc/api/H5.php?chapter=15_4
		String result = paymentSetting.wapPayment(new HashMap<String, String>(16) {
			{
				put("redirect_url", weChatPaymentProperties.getRedirecturl());
			}
		});

		log.info("===========WeChatPayment========redirect_url:" + result);
		// TODO 推荐商品

		return RestfulResult.ok(result);
	}

}
